import BasicConfig from "../utils/config";
import {
  useGetLocationStorage,
  useSetLnglatStorage,
  useSetLocationStorage,
} from "./useStorage";
import qs from "qs";

/**
 * 获取当前定位逆向解析地址信息
 * type: gcj02
 * cache: 是否缓存解析后的信息
 * 因当前业务为上门保洁服务，需获取用户地理位置信息匹配最近的上门保洁产品服务信息供用户下单预约，并进行坐标逆向解析回显给客户，完成商品交易闭环流程，故申请 wx.getLocation 接口，用于匹配最近保洁产品提供保洁服务，感谢~
 * 因当前业务为保洁服务，需要获取用户地理位置信息，所在省市地区信息予以展示并匹配最近的保洁产品服务信息供用户预约使用，故申请 wx.getLocation 接口，用于匹配最近保洁产品提供保洁服务，感谢~
 */
export const useGetLocationAddress = async (type = "gcj02", Cache = true) => {
  return new Promise((resolve, reject) => {
    uni.getSetting({
      success: (setRes) => {
        const userLocation = setRes.authSetting["scope.userLocation"];
        console.log("getSetting useGetLocationAddress", userLocation);
        if (userLocation === undefined) {
          _getLocation(resolve, reject, type, Cache);
        } else if (userLocation === true) {
          _getLocation(resolve, reject, type, Cache);
        } else {
          _openSetting(resolve, reject, type, Cache);
        }
      },
      fail: (error) => {},
    });
  });
};

export const _getLocation = (resolve, reject, type = "gcj02", Cache = true) => {
  uni.getLocation({
    type,
    success: function (res) {
      console.log("getLocation api:", res);
      if (res.errMsg === "getLocation:ok") {
        const latitude = res.latitude;
        const longitude = res.longitude;
        const key = BasicConfig.mapKey;
        const params = {
          location: `${latitude},${longitude}`,
          key,
          get_poi: 1,
          poi_options: "poi_options=policy=2",
        };
        const query = qs.stringify(params);
        console.log("url", `https://apis.map.qq.com/ws/geocoder/v1/?${query}`);
        uni.request({
          url: `https://apis.map.qq.com/ws/geocoder/v1/?${query}`,
          data: {},
          success: (ress) => {
            console.log("地址解析", ress);
            if (ress.errMsg === "request:ok") {
              if (Cache) {
                const ad_info = ress.data?.result?.ad_info || null;
                if (ad_info) {
                  let cityCode = ad_info.city_code;
                  cityCode = cityCode
                    .replace(new RegExp(ad_info.nation_code), "")
                    .slice(0, 4);
                  useSetLocationStorage({
                    code: cityCode,
                    name: ad_info.city,
                  });
                  useSetLnglatStorage({
                    lat: latitude,
                    lng: longitude,
                  });
                }
              }
              resolve(ress);
            } else {
              useSetLocationStorage(BasicConfig.dfCityCode);
              useSetLnglatStorage(BasicConfig.dfLatLng);
              reject({ msg: "解析失败" });
            }
          },
          fail(err) {
            console.error("GetLocation[fail]", err);
            useSetLocationStorage(BasicConfig.dfCityCode);
            useSetLnglatStorage(BasicConfig.dfLatLng);
            reject({ msg: "解析失败" });
          },
        });
      }
      console.log("useGetLocation", res);
    },
    fail(err) {
      useSetLocationStorage(BasicConfig.dfCityCode);
      useSetLnglatStorage(BasicConfig.dfLatLng);
      console.error("GetLocation[fail]", err);
      reject({ msg: "解析失败" });
    },
  });
};

/**
 * 获取用户是否授权位置信息
 */
export const useGetAuthLocation = async () => {
  return new Promise((resolve, reject) => {
    uni.getSetting({
      success: (setRes) => {
        const key = "scope.userLocation";
        const { authSetting } = setRes;
        console.log("useGetAuthLocation[key]", authSetting[key]);
        // 是否未授权
        const Auth = authSetting[key] == undefined || !authSetting[key];
        resolve(!Auth);
      },
    });
  });
};

/**
 * 获取当前定位逆向解析地址信息(未用)
 * type: gcj02 wgs84
 * cache: 是否缓存解析后的信息
 * https://developers.weixin.qq.com/community/develop/doc/000646718d40a08a65ed1e2175bc09
 * 开发者因涉及营销活动，希望申请wx.getLocation接口便于帮助用户定位所在位置，
 * 但根据服务内容可知当前仅需获取用户所在城市/地区，无需通过wx.getLocation获取详细的经纬度定位，
 * 使用wx.getFuzzyLocation、wx.chooseLocation或wx.choosePoi接口实现上述场景
 * 房地产、餐饮、商家自营等小程序，希望申请wx.getLocation接口获取用户当前实时位置信息，
 * 为用户展示附近、周边门店信息，提供推荐营销服务，且小程序内未提供线下门店导航服务，仅在小程序内为用户提供附近、周边门店信息展示服务，
 * 该场景不支持使用wx.getLocation、wx.onLocationchange这类高精度位置接口，
 * 建议开发者使用wx.getFuzzylocation、wx.chooseLocation或wx.choosePoi实现上述场景。
 */
export const useGetFuzzyAddress = (type = "gcj02", Cache = true) => {
  return new Promise((resolve, reject) => {
    uni.getSetting({
      success: (setRes) => {
        console.log("getSetting", setRes);
        const userFuzzyLocation = setRes.authSetting["scope.userFuzzyLocation"];
        console.log("userFuzzyLocation", userFuzzyLocation);
        if (userFuzzyLocation === undefined) {
          _getFuzzyLocation(resolve, reject, type, Cache);
        } else if (userFuzzyLocation === true) {
          _getFuzzyLocation(resolve, reject, type, Cache);
        } else {
          _openSetting(reject);
        }
      },
      fail: (error) => {},
    });
  });
};
export const _getFuzzyLocation = (
  resolve,
  reject,
  type = "gcj02",
  Cache = true
) => {
  uni.getFuzzyLocation({
    type,
    success: function (res) {
      console.log("getFuzzyLocation api:", res);
      if (res.errMsg === "getFuzzyLocation:ok") {
        const latitude = res.latitude;
        const longitude = res.longitude;
        const key = BasicConfig.mapKey;
        const params = {
          location: `${latitude},${longitude}`,
          key,
          get_poi: 1,
          poi_options: "poi_options=policy=2",
        };
        const query = qs.stringify(params);
        console.log("url", `https://apis.map.qq.com/ws/geocoder/v1/?${query}`);
        uni.request({
          url: `https://apis.map.qq.com/ws/geocoder/v1/?${query}`,
          data: {},
          success: (ress) => {
            console.log("getFuzzyLocation 地址解析", ress);
            if (ress.errMsg === "request:ok") {
              if (Cache) {
                const ad_info = ress.data?.result?.ad_info || null;
                if (ad_info) {
                  let cityCode = ad_info.city_code;
                  cityCode = cityCode
                    .replace(new RegExp(ad_info.nation_code), "")
                    .slice(0, 4);
                  useSetLocationStorage({
                    code: cityCode,
                    name: ad_info.city,
                  });
                }
              }
              resolve(ress);
            } else {
              _openSetting(reject);
              useSetLocationStorage(BasicConfig.dfCityCode);
              reject({ msg: "解析失败" });
            }
          },
        });
      } else {
        useSetLocationStorage(BasicConfig.dfCityCode);
      }
      console.log("useGetFuzzyAddress", res);
    },
    fail(err) {
      _openSetting(reject);
      useSetLocationStorage(BasicConfig.dfCityCode);
      reject({ msg: "解析失败" });
      console.error("useGetFuzzyAddress[fail]", err);
    },
  });
};
const _openSetting = (resolve, reject, type, Cache) => {
  setTimeout(() => {
    uni.showModal({
      title: "未授权地理位置",
      content:
        "您未授权地理位置，将无法正常获取附近的服务，您可在设置中打开地理位置开关",
      confirmText: "去设置",
      confirmColor: BasicConfig.MainColor,
      success(success) {
        console.log("_openSetting", success);
        if (success.confirm) {
          uni.openSetting({
            success: (ress) => {
              uni.getSetting({
                success: (setRes) => {
                  const userLocation = setRes.authSetting["scope.userLocation"];
                  console.log("getSetting useGetLocationAddress", userLocation);
                  if (userLocation === undefined) {
                    _getLocation(resolve, reject, type, Cache);
                  } else if (userLocation === true) {
                    _getLocation(resolve, reject, type, Cache);
                  } else {
                    useSetLocationStorage(BasicConfig.dfCityCode);
                    useSetLnglatStorage(BasicConfig.dfLatLng);
                    reject({ msg: "拒绝授权" });
                  }
                },
                fail: (error) => {
                  useSetLocationStorage(BasicConfig.dfCityCode);
                  useSetLnglatStorage(BasicConfig.dfLatLng);
                  reject({ msg: "拒绝授权" });
                },
              });
              // console.log("openSetting", ress);
              // _getLocation(resolve, reject, type, Cache);
            },
            fail: (error) => {
              useSetLocationStorage(BasicConfig.dfCityCode);
              useSetLnglatStorage(BasicConfig.dfLatLng);
              reject({ msg: "拒绝授权" });
              console.log("openSetting error", error);
            },
          });
        } else {
          useSetLocationStorage(BasicConfig.dfCityCode);
          useSetLnglatStorage(BasicConfig.dfLatLng);
          reject({ msg: "拒绝授权" });
        }
      },
    });
  }, 800);
};

/**
 * 获取经纬度对应的逆向解析地址信息
 */
export const useGetLocationReverseAnalysis = (params) => {
  return new Promise((resolve, reject) => {
    const { lat, lng } = params;
    const latitude = lat;
    const longitude = lng;
    const key = BasicConfig.mapKey;
    const requestParams = {
      location: `${latitude},${longitude}`,
      key,
      get_poi: 1,
      poi_options: "poi_options=policy=2",
    };
    const query = qs.stringify(requestParams);
    console.log("url", `https://apis.map.qq.com/ws/geocoder/v1/?${query}`);
    uni.request({
      url: `https://apis.map.qq.com/ws/geocoder/v1/?${query}`,
      data: {},
      success: (ress) => {
        console.log("地址解析", ress);
        resolve(ress);
      },
    });
  });
};
